-- file : application.lua
local module = {}  
m = nil

-- Sends a simple ping to the broker
local function send_ping()  
    m:publish(config.ENDPOINT .. "ping","id=" .. config.ID,0,0)
    if wifi.sta.getip()== nil then
        setup.start()
    end
end

-- Sends my id to the broker for registration
local function register_myself()  
    m:subscribe(config.ENDPOINT .. config.ID,0,function(conn)
        print("Successfully subscribed to data endpoint")
    end)
end

local function mqtt_start()
    m = mqtt.Client(config.ID, 120)
    -- register message callback beforehand
    m:on("message", function(conn, topic, data) 
      if data ~= nil then
		print(data)
        -- print(topic .. ": " .. data)
		-- relay.rlyctl()
        -- do something, we have received a message
      end
    end)
    m:on("offline", function(conn) 
        node.restart()
    end)
    -- Connect to broker
    m:connect(config.HOST, config.PORT, 0, 1, function(con) 
		print("connecting to mqtt server")
        register_myself()
        -- And then pings each 1000 milliseconds
        tmr.stop(6)
        tmr.alarm(6, 1000, 1, send_ping)
    end)
end

function module.start() 
	print("starting mqtt service!") 
	mqtt_start()
end

return module  